let express = require("express");
let multer = require("multer");
const upload = multer({ dest: "upload/" });
let fs = require("fs");
let path = require("path");
let router = express.Router();

router.post("/uploads", upload.single("file"), (req, res) => {
    fs.readFile(req.file.path, (err, data) => {
        if (err) {
            return res.send("上传失败");
        }
        // 设置不会重复的名字
        let time = Date.now() + (Math.random() * 999 + parseInt(Math.random() * 2222));
        // 拿取后缀名
        let extname = req.file.mimetype.split("/")[1];
        // 合并最终的名字
        let keepname = time + "." + extname;
        // 参数一：存的位置
        // 参数二：写入的内容
        // 参数三：回调函数
        fs.writeFile(path.join(__dirname, "../upload/" + keepname), data, (err) => {
            if (err) {
                return res.send("写入失败" + err);
            }
            // 删除二进制文件(不做这一步会多存一个二进制文件)
            fs.unlinkSync(req.file.path);
            res.send({ err: 200, m: "上传成功", src: keepname });
        });
    });
});

module.exports = router;
